package com.finger.statisticsservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.finger.commonutils.JwtUtils;
import com.finger.commonutils.R;
import com.finger.statisticsservice.entity.Order;
import com.finger.statisticsservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author finger
 * @since 2022-01-27
 */
@CrossOrigin
@RestController
@RequestMapping("/orderservice/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 根据请求头中带的token，获取用户id，根据用户id和路径中传入的课程id创建订单，并返回订单号
     * @param courseId 课程Id
     * @param req 请求
     * @return 订单号
     */
    @PostMapping("/createOrders/{courseId}")
    public R createOrders(@PathVariable("courseId") String courseId, HttpServletRequest req){

        String orderNo = orderService.createOrders(courseId, JwtUtils.getMemberIdByJwtToken(req));

        return R.ok().data("orderNo",orderNo);
    }

    /**
     * 根据路径中传入的订单号获取订单对象，并返回
     * @param orderNo 订单号
     * @return 返回订单对象
     */
    @GetMapping("/getOrders/{orderNo}")
    public R getOrders(@PathVariable("orderNo") String orderNo){

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("order_no",orderNo);

        Order order = orderService.getOne(orderQueryWrapper);

        return R.ok().data("order",order);
    }

    @GetMapping("/isBuy/{courseId}/{memberId}")
    public boolean isBuy(@PathVariable String courseId
            ,@PathVariable String memberId){

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("course_id",courseId);

        orderQueryWrapper.eq("member_id",memberId);

        orderQueryWrapper.eq("status",1);
        int count = orderService.count(orderQueryWrapper);

        return count==1;
    }
}

